package javatest;

import com.vpx.JniVpx;
import java.io.File;

/**
 * @author sad
 */
public class Utils {

    public static void arrayPutShort(byte[] mem, int offset, short val) {
        mem[1 + offset] = (byte) val;
        mem[0 + offset] = (byte) (val >> 8);
    }

    public static void arrayPutInt(byte[] mem, int offset, int val) {
        mem[3 + offset] = (byte) val;
        mem[2 + offset] = (byte) (val >> 8);
        mem[1 + offset] = (byte) (val >> 16);
        mem[0 + offset] = (byte) (val >> 24);
    }

    public static short arrayGetShort(byte[] mem, int offset) {
        int value;
        value = mem[1 + offset] & 0xff;
        value |= (mem[0 + offset] << 8) & 0xffff;
        return (short) value;
    }

    public static int arrayGetInt(byte[] mem, int offset) {
        int value;
        value = mem[0 + offset] & 0xff;
        value = value << 8;
        value |= (mem[1 + offset] & 0xff);
        value = value << 8;
        value |= (mem[2 + offset] & 0xff);
        value = value << 8;
        value |= (mem[3 + offset] & 0xff);
        return value;
    }

    public static void loadLibraries() {
        String absPath = new File(".").getAbsolutePath();
        absPath = absPath.substring(0, absPath.length() - 1);
        System.out.println("Path=" + absPath);
        String[] filesPaths = new String[]{
            "d:\\jnijvpx8.dll",
            "F:\\java\\many-different-my-project\\vpx\\jnijvpx8\\Debug\\jnijvpx8.dll",
            "d:\\java\\many-different-my-project\\vpx\\jnijvpx8\\Debug\\jnijvpx8.dll",
            "d:\\java\\many-different-my-project\\vpx\\jnijvpx8\\Release\\jnijvpx8.dll",
            absPath + "jnijvpx8.dll"
        };
        String libPath = null;
        for (String path : filesPaths) {
            if (new File(path).exists()) {
                libPath = path;
                break;
            }
        }
        if (libPath == null) {
            throw new UnsatisfiedLinkError("Cannot find library jnijvpx8.dll");
        }

        System.load(libPath);

        filesPaths = new String[]{
            "d:/vpx.dll",
            "d:/java/many-different-my-project/vpx/vpx.dll",
            "f:\\java\\many-different-my-project\\vpx\\vpx.dll",
            absPath + "vpx.dll"
        };
        libPath = null; 
        for (String path : filesPaths) {
            if (new File(path).exists()) {
                libPath = path;
                break;
            }
        }
        if (libPath == null) {
            throw new UnsatisfiedLinkError("Cannot find library vpx.dll");
        }

        JniVpx.loadVpxLib(libPath);
    }
}
